package com.seal.tsms.base.service;

import com.seal.tsms.base.dao.BaseDao;
import com.seal.tsms.base.dao.Pagination;
import com.seal.tsms.base.dao.QueryParser;
import com.seal.tsms.base.log.BaseLog;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by seal.jing on 2015/12/24.
 */
@Transactional
public abstract class AbstractBaseService<E extends Serializable,PK extends Serializable> extends BaseLog implements BaseService<E,PK> {
    private BaseDao<E,PK> selfDao;


    public BaseDao<E, PK> getSelfDao() {
        return selfDao;
    }

    @Autowired
    public void setSelfDao(BaseDao<E, PK> selfDao) {
        this.selfDao = selfDao;
    }

    public void save(E entity) {
        this.selfDao.save(entity);
    }

    public void update(E entity) {
        this.selfDao.update(entity);

    }

    public void delete(E entity) {
        this.selfDao.delete(entity);

    }

    public void merge(E entity) {
        this.selfDao.merge(entity);

    }

    public E get(PK id) {
        return this.selfDao.get(id);
    }

    public E findOne(String dsl, Map params) {

       dsl=ParamsFilter.build(dsl,params);

        return this.selfDao.findOne(dsl,params);
    }

    public E findOne(DetachedCriteria detachedCriteria) {

        return this.selfDao.findOne(detachedCriteria);
    }

    public void browse(Pagination pagination) {
        Object condition=pagination.getCondition();
        if(condition instanceof  Map) {
            Map map = (Map) condition;
            if (map.containsKey(Pagination.RESULT_HQL) && map.containsKey(Pagination.PARAMS)){
                String hql=ParamsFilter.build(map.get(Pagination.RESULT_HQL).toString(), (Map<String, ?>) map.get(Pagination.PARAMS));
                String count_hql=ParamsFilter.buildCount(hql);
                map.put(Pagination.COUNT_HQL,count_hql);
                map.put(Pagination.RESULT_HQL,hql);
            }

            this.selfDao.browse(pagination);
        }else{
            throw new RuntimeException("查询条件不符合规范");
        }

    }

    public List<?> list(String dsl, Map params,ResultTransformer resultTransformer) {
        dsl=ParamsFilter.build(dsl,params);
        return this.selfDao.list(dsl,params,0,0,resultTransformer);
    }

    public List<?> list(DetachedCriteria detachedCriteria,ResultTransformer resultTransformer) {
        return this.selfDao.list(detachedCriteria,0,0,resultTransformer);
    }

    public void batch(String named, Map params) {
        named=ParamsFilter.build(named,params);
        this.selfDao.batch(named,params);

    }
}
